package com.bdth.service.impl;

import com.bdth.mapper.DeviceMapper;
import com.bdth.mapper.EnclosureBindMapper;
import com.bdth.model.EnclosureBind;
import com.bdth.service.IEnclosureBindService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class EnclosureBindServiceImpl extends BaseServiceImpl<EnclosureBind> implements IEnclosureBindService {

	@Autowired
	private SqlSessionTemplate sqlSession;

	@Autowired
	private EnclosureBindMapper mapper;

	@Override
	public void updateBatch(List<EnclosureBind> list) throws Exception {
		// 新获取一个模式为BATCH，自动提交为false的session
		// 如果自动提交设置为true,将无法控制提交的条数，改为最后统一提交，可能导致内存溢出
		SqlSession session = sqlSession.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
		try {
			int batchCount = 50;// 每批commit的个数
			int batchLastIndex = batchCount;// 每批最后一个的下标
			for (int index = 0; index < list.size(); ) {
				if (batchLastIndex >= list.size()) {
					batchLastIndex = list.size();
					sqlSession.insert("com.bdth.mapper.EnclosureBindMapper.updateBatch", list.subList(index, batchLastIndex));
					//System.out.println("index:" + index + " batchLastIndex:" + batchLastIndex);
					break;// 数据更新完毕，退出循环
				} else {
					sqlSession.insert("com.bdth.mapper.EnclosureBindMapper.updateBatch", list.subList(index, batchLastIndex));
					//System.out.println("index:" + index + " batchLastIndex:" + batchLastIndex);
					index = batchLastIndex;// 设置下一批下标
					batchLastIndex = index + (batchCount - 1);
				}
			}
		} catch (Exception e) {
			// 没有提交的数据可以回滚
			session.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	@Override
	public List<Map> queryBindEnclosures(Map map) throws Exception {
		return mapper.queryBindEnclosures(map);
	}
}
